/**
 * 21. 合并两个有序链表
 */
class Solution1 {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode tmp = new ListNode();
        ListNode cur = tmp;
        while(list1 != null && list2 != null){
            if(list1.val < list2.val){
                cur.next = list1;
                cur = list1;
                list1 = list1.next;
            }else{
                cur.next = list2;
                cur = list2;
                list2 = list2.next;
            }
            
        }
        if(list1 != null){
            cur.next = list1;
        }
        if(list2 != null){
            cur.next = list2;

        }
        cur = tmp.next;
        return cur;
    }
}

/**
 * 链表中倒数第k个结点 牛客
 */
public class Solution2 {
    public ListNode FindKthToTail(ListNode head,int k) {
        if(k <= 0 || head == null ){
            return null;
        }
        ListNode fast = head;

        ListNode slow = head;
        while(k-1 > 0){

            fast = fast.next;
            if(fast== null){    //替代判断k是否大于数组长度
                return null;
            }
            k--;
        }
        while(fast.next != null){
            fast = fast.next;
            slow = slow.next;
        }

        return slow;
    }
}

/**
 * 876. 链表的中间结点
 */
class Solution3 {
    public ListNode middleNode(ListNode head) {
        //快慢指针
        ListNode fast = head;
        ListNode slow = head;
        //fast是slow的速度2倍，当fast为null，slow恰好在中间，slow走的是fast走的距离的二分之一的距离
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
}

/**
 * 203. 移除链表元素
 */
class Solution4 {
    public ListNode removeElements(ListNode head, int val) {
        if(head == null){
            return null;
        }
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null){
            //如果当前fast.val == key 那么slow.next 记录fast的下一个位置
            if(fast.val == val){
                slow.next = fast.next;
            }else{
                //否则 slow 走到 fast当前位置
                slow = fast;
            }
            fast = fast.next;
        }
        //删除头
        if(head.val == val){
            head = head.next;
        }
        return head;
    }
}

/**
 * 206. 反转链表
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null){
            return null;
        }
        if(head.next == null){
            return head;
        }
        //从第二个开始
        ListNode cur = head.next;
        //第一个节点置为null
        head.next = null;
        while(cur != null){
            //提前记录下一个节点
            ListNode tmp = cur.next;
            //进行头插法
            cur.next = head;
            head = cur;
            //cur指向下一个节点
            cur = tmp;
        }
        return head;

    }